package com.atguigu.distributed.lock.leecode;

import java.util.Random;

public class FindKthLargest {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8,10,9};
        int[] arr2 = {1,2,4,3,5,6,8,7,10,9};
        FindKthLargest findKthLargest = new FindKthLargest();
        int i1 = findKthLargest.partition2(arr2, 6, arr2.length - 1);
        System.out.println("res==>"+i1);
        for (int i = 0; i < arr2.length; i++) {
            System.out.println("every==>"+arr2[i]);
        }
        System.out.println(findKthLargest.findKthLargest2(arr,2));
    }

    Random random = new Random();

    public int findKthLargest(int[] nums, int k) {
        return quickSelect(nums, 0, nums.length - 1, nums.length - k);
    }
    public int findKthLargest2(int[] nums,int k){
        return quickSelect2(nums,0,nums.length-1,nums.length-k);
    }

    public int quickSelect(int[] a, int l, int r, int index) {
        int q = randomPartition(a, l, r);
        if (q == index) {
            return a[q];
        } else {
            return q < index ? quickSelect(a, q + 1, r, index) : quickSelect(a, l, q - 1, index);
        }
    }

    public int quickSelect2(int[] a, int left, int right, int index) {
        int q = randomPartition2(a, left, right);
        if (q == index) {
            return a[q];
        } else {
            return q < index ? quickSelect2(a, q + 1, right, index) : quickSelect2(a, left, q - 1, index);
        }
    }

    public int randomPartition2(int[] a, int left, int right) {
        int index = random.nextInt(right - left + 1) + left;
        swap(a, index, right);
        return partition2(a, left, right);
    }

    public int randomPartition(int[] a, int l, int r) {
        int i = random.nextInt(r - l + 1) + l;
        swap(a, i, r);
        return partition2(a, l, r);
    }

    public int partition2(int[] a, int left, int right) {
        int x = a[right], i = left - 1;
        for (int j = left; j < right; ++j) {
            if (a[j] <= x) {
                swap(a, ++i, j);
            }
        }
        swap(a, i + 1, right);
        return i + 1;
    }

    public int partition(int[] a, int l, int r) {
        int x = a[r], i = l - 1;
        for (int j = l; j < r; ++j) {
            if (a[j] <= x) {
                swap(a, ++i, j);
            }
        }
        swap(a, i + 1, r);
        return i + 1;
    }

    public void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

}
